<?php 
 
class TabularModel extends fpp_tdp_Model{

  private $secondM = null;

  function __construct($DataObjects){
    parent::__construct($DataObjects);
  }

  public function __toString(){
    $Model =  $this->args->model.'_Model';
    $Model = new $Model;
    $firstM = $this->attributes->NameModel;
    $metaModel = $Model->Get_Meta();
    foreach($metaModel as $field => $ref){
//     echo Kohana::debug($field);
      $ModelIn = explode("(model=",$ref);
//       echo Kohana::debug($ModelIn);
      if(count($ModelIn) > 1){
        $ComNameMod = substr($ModelIn[1],0,-1)."_Model";
        if(!($ComNameMod == $this->attributes->NameModel)){
          $this->FSecondM = $field;
          $this->secondM = substr($ModelIn[1],4,-1);
        }else{        
          $this->FFirstM = $field;
          $this->FirstM = substr($ModelIn[1],4,-1);
        }
      }
    }
    
    return $this->_DropDown();
  }
  
  private function _DropDown(){
    $tabla_conectora = substr($this->args->model,4);
    if(@$_SESSION['PKID_OTM'] <> ""){
      try {
        $arrOTMnew = array($this->FFirstM => $this->PkID, $this->FSecondM => $_SESSION['PKID_OTM'] );
        $this->db->insert($tabla_conectora,$arrOTMnew);
        unset($_SESSION['PKID_OTM']);
      } catch (Exception $e) {
          echo 'Caught exception: ',  $e->getMessage(), "\n";
      }
    }
    /* Construyendo el Query */    
    $Model =  "fpp_".$this->secondM.'_Model';
    $input = null;
    $Model = new $Model;    
    $list = $Model->Get_ListOfMeta();
    $key = $Model->_FirstPrimary;
    $this->args->db_table = $this->secondM; //compatibilidad para obtener el Link AJAX fpp_tdp #34
    $k1 = '`'.$tabla_conectora."`.`".$this->FFirstM.'`';
    $k2 = '`'.$tabla_conectora."`.`".$this->FSecondM.'`';
    $f2 = '`'.$this->secondM."`.`".$key.'`';
    $idfpp = $this->PkID;
    try {
//       echo $k1;
       $one_to_one=$this->db->from($this->secondM,$tabla_conectora)->select($list)->where( "$k1 = $idfpp AND $k2 = $f2"  )->get();
    } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
    /* Construyendo el Array del Dropdown */
    $table = "<table>";
    foreach($one_to_one as $row){
      $table .= "<tr>";
      $input .= form::hidden($this->field_name.'[]',$row->$key);
      foreach($row as $kr => $kv){        
        $table .= "<td>{$kv}</td>";
      }
      $table .= "</tr>";
    }    
    $table .= "</table>".$input;
     $table = $this->AjaxConstruct( "&nbsp;").'<br/>'.$table ;
     return $table;
  }
}

?>